﻿using Microsoft.AspNetCore.Authorization;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace InfrastructureBase.Base.AuthBase.CustomAuth.Authorization
{
    /// <summary>
    /// 自定义 Handler 程序继承 AuthorizationHandler<TRequirement> 并重写 HandleRequirementAsync 方法
    /// </summary>
    public class CustomAuthorizationHandler : AuthorizationHandler<CustomAuthorizationRequirement>
    {
        protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, CustomAuthorizationRequirement requirement)
        {
            var permissions = context.User.Claims.Where(_ => _.Type == "Permission").Select(_ => _.Value).ToList();
            if (permissions.Any(_ => _.StartsWith(requirement.Name)))
            {
                context.Succeed(requirement);
            }
            return Task.CompletedTask;
        }
    }
}
